import { Injectable, HttpException } from '@nestjs/common';
import { PrismaService } from '../prisma.service';
import { Prisma } from '@prisma/client';
import * as bcrypt from 'bcrypt';

@Injectable()
export class UserService {
  constructor(private prisma: PrismaService) { }

  // 创建用户
  async create(data: Prisma.UserCreateInput) {
    const existUser = await this.prisma.user.findUnique({
      where: { userName: data.userName }
    });

    if (existUser) {
      throw new HttpException('用户名已存在', 400);
    }

    // 密码加密
    const hashedPassword = await bcrypt.hash(data.password, 10);

    return this.prisma.user.create({
      data: {
        ...data,
        password: hashedPassword
      }
    });
  }

  // 更新用户
  async update(id: number, data: Prisma.UserUpdateInput) {
    if (data.password) {
      data.password = await bcrypt.hash(data.password as string, 10);
    }

    return this.prisma.user.update({
      where: { id },
      data
    });
  }

  // 删除用户
  async delete(id: number) {
    return this.prisma.user.delete({
      where: { id }
    });
  }

  // 获取用户列表
  async findAll(params: {
    skip?: number;
    take?: number;
    where?: Prisma.UserWhereInput;
    orderBy?: Prisma.UserOrderByWithRelationInput;
  }) {
    const { skip, take, where, orderBy } = params;
    const [total, items] = await Promise.all([
      this.prisma.user.count({ where }),
      this.prisma.user.findMany({
        skip,
        take,
        where,
        orderBy,
        include: {
          userRoles: {
            include: {
              role: true
            }
          }
        }
      })
    ]);

    return {
      items,
      total
    };
  }

  // 获取用户详情
  async findOne(id: number) {
    return this.prisma.user.findUnique({
      where: { id },
      include: {
        userRoles: {
          include: {
            role: true
          }
        }
      }
    });
  }

  // 重置密码
  async resetPassword(id: number, newPassword: string) {
    const hashedPassword = await bcrypt.hash(newPassword, 10);
    return this.prisma.user.update({
      where: { id },
      data: { password: hashedPassword }
    });
  }

  // 更新用户角色
  async updateUserRoles(userId: number, roleIds: number[]) {
    // 先删除原有角色
    await this.prisma.userRole.deleteMany({
      where: { userId }
    });

    // 添加新角色
    const userRoles = roleIds.map(roleId => ({
      userId,
      roleId
    }));

    await this.prisma.userRole.createMany({
      data: userRoles
    });

    return await this.findOne(userId);
  }
}
